package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class CampaignTeamController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService
    def exportService

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def campaignTeamList = CampaignTeam.findAll("from CampaignTeam where user.username = '${username}' order by modifiedDate desc", [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = CampaignTeam.executeQuery("select count(id) from CampaignTeam where user.username = '${username}'")

        respond campaignTeamList, model: [campaignTeamCount: count[0], params: params]

    }

    def show(CampaignTeam campaignTeam)
    {
        respond campaignTeam
    }

    def create()
    {
        def campaign = Campaign.findById(params['campaign'])
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        if (campaign?.user == user || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            def userList = User.list()
            def campaignTeams = CampaignTeam.findAllByCampaign(campaign)
            campaignTeams?.each {
                userList -= it?.user
            }
            respond new CampaignTeam(params), model: [userList: userList]
        }
        else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "campaign", action: "show", params: [id: campaign.id])
            return
        }
    }

    @Transactional
    def save(CampaignTeam campaignTeam)
    {
        def userList = User.list()
        def campaignTeams = CampaignTeam.findAllByCampaign(campaignTeam?.campaign)
        campaignTeams?.each {
            userList -= it?.user
        }

        if (campaignTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (campaignTeam.hasErrors())
        {
            //COMMENT THE INFO THEN YOU WILL SEE MIRACLES
            log.info "userList:" + userList

            transactionStatus.setRollbackOnly()
            respond campaignTeam.errors, model: [userList: userList], view: 'create'
            return
        }

        campaignTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'campaignTeam.label', default: 'CampaignTeam'), campaignTeam.id])
                redirect(controller: 'campaign', action: 'show', params: [id: campaignTeam?.campaign?.id])
            }
            '*' { respond campaignTeam, [status: CREATED] }
        }
    }

    def edit(CampaignTeam campaignTeam)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def user = User.findByUsername(username)

        TeamRole editTeamRole = TeamRole.findByName('Edit')
        CampaignTeam currentCampaignTeam = CampaignTeam.findByCampaignAndUser(campaignTeam.campaign, user)

        if (campaignTeam.campaign.user.id == user.id || currentCampaignTeam?.teamPermission?.id == editTeamRole.id)
        {
            respond campaignTeam, model: [user: user]
        }
        else
        {
            flash.message = "没有编辑权限"
            redirect controller: "campaign", action: "show", id: campaignTeam.campaign.id
        }
    }

    @Transactional
    def update(CampaignTeam campaignTeam)
    {
        if (campaignTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (campaignTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond campaignTeam.errors, view: 'edit'
            return
        }

        campaignTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'campaignTeam.label', default: 'CampaignTeam'), campaignTeam.id])
                // redirect campaignTeam
                redirect controller: "campaign", action: "show", id: campaignTeam?.campaign?.id
            }
            '*' { respond campaignTeam, [status: OK] }
        }
    }

    @Transactional
    def delete(CampaignTeam campaignTeam)
    {

        if (campaignTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        campaignTeam.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'campaignTeam.label', default: 'CampaignTeam'), campaignTeam.id])
                redirect(controller: 'campaign', action: 'show', params: [id: campaignTeam?.campaign?.id])
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'campaignTeam.label', default: 'CampaignTeam'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def searchCampaignTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        String name = params["name"]
        String type = params["type"]

        String sql = "from CampaignTeam as u where u.user.username = '${username}'"
        if (name)
        {
            sql += " and u.campaign.name like '%${name}%'"
        }
        if (type)
        {
            sql += " and u.campaign.type.name like '%${type}%'"
        }
        String countSql = "select count(u.id) " + sql
        sql += " order by u.modifiedDate desc"

        def list = CampaignTeam.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = CampaignTeam.executeQuery(countSql)

        respond list, model: [campaignTeamCount: count[0], params: params], view: 'index'
    }

    def exportCampaignTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        String name = params["name"]
        String type = params["type"]

        String sql = "from CampaignTeam as u where u.user.username = '${username}'"
        if (name)
        {
            sql += " and u.campaign.name like '%${name}%'"
        }
        if (type)
        {
            sql += " and u.campaign.type.name like '%${type}%'"
        }
        String countSql = "select count(u.id) " + sql
        sql += " order by u.modifiedDate desc"

        def list = CampaignTeam.findAll(sql)
        def count = CampaignTeam.executeQuery(countSql)

        if (params?.f && params.f != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.f]
            response.setHeader("Content-disposition", "attachment; filename=campaignTeam.${params.extension}")
            List fields = ["campaign.name", "campaign.status.name", "campaign.parent.name", "campaign.type.name", "campaign.territory.name", "campaign.startTime", "campaign.endTime", "campaign.description", "campaign.active", "campaign.createdDate", "campaign.modifiedDate"]
            Map labels = ["campaign.name": "名称", "campaign.status.name": "状态", "campaign.parent.name": "父级市场活动", "campaign.type.name": "类型", "campaign.territory.name": "区域", "campaign.startTime": "开始时间", "campaign.endTime": "结束时间", "campaign.description": "描述", "campaign.active": "启用", "campaign.createdDate": "创建时间", "campaign.modifiedDate": "修改时间"]
            exportService.export(params.f, response.outputStream, list, fields, labels, [:], [:])
        }
    }
}
